import React, {useEffect, useState} from 'react'
import { useNavigate } from 'react-router-dom';
import { Button,  Form, Input, Switch, Select, message, Upload, Image  } from 'antd';
import { UploadOutlined } from '@ant-design/icons'
import {fetchCateLists} from '../../api/cateLists' //商品分类请求接口
import {addItem} from '../../api/itemLists'
import '@wangeditor/editor/dist/css/style.css'//引入富文本的css
import { Editor, Toolbar } from '@wangeditor/editor-for-react'
 function ItemAdd() {
  const navigate = useNavigate()
  const [cates, setCates] = useState([])
  useEffect(() => { //初始化请求所有商品分类
    fetchCateLists().then(res => {
      if (res.data.code === 200) {
        const cate = res.data.data.lists.map(item => {
          return {
              value: item.id,
              label: item.cateName
          }
              })
              setCates([
                {
                    value: -1,
                    label: '请选择分类'
                },
                ...cate
            ])
      }
    })
  }, [])

  //表单提交
  const onFinish = (values) => { //表单提交成功时触发的回调
    values.thumb = thumb //上传后返回来的图片地址
    values.content = html
    addItem(values).then(res => {
      if ( res.data.code === 200) {
        message.success(res.data.msg, 2, () => {
          navigate('/itemLists', {replace: true})
        })
      }
    })
  };
  const onFinishFailed = (errorInfo) => {//表单提交失败时触发的回调
    console.log('Failed:', errorInfo);
  };
  //表单提交
  
  //商品分类的下拉菜单的数据
  const options = cates
 
  //商品分类的下拉菜单的数据

//商品描述
const { TextArea } = Input;
//商品描述

//文件上传的数据和配置
const [thumb, setThumb] = useState('')
const _props = {
  action: "/api/upload",
  accept:'image/*', //接受上传的文件类型
  onChange(info) {//上传文件改变时的回调
    
    if (info.file.status === 'done') {
      setThumb(info.file.response.data.url)
    } 
  },
};
//文件上传的数据和配置

//富文本编译器
const [editor, setEditor] = useState(null);
  const [html, setHtml] = useState('');
  const toolbarConfig = {}
  const editorConfig = {                         // JS 语法
    placeholder: '请输入内容...',
    MENU_CONF: {
      uploadImage: {
        server: '/api/upload',
        fieldName: 'file',
        customInsert: (res, insertFn) => {
          
          insertFn(res.data.url)
        }
      }
    }
  }

//富文本编译器

  return (
    <div>
       <Form
      name="basic"
      labelCol={{
        span: 4,
        onsale: true
      }}
      wrapperCol={{
        span: 20,
      }}
      initialValues={{
        pid: -1
      }}
      onFinish={onFinish}//表单提交成功时触发的回调
      onFinishFailed={onFinishFailed}//表单提交失败时触发的回调
      autoComplete="off"
    >
      <Form.Item
        label="商品名称"
        name="itemName"
        wrapperCol = {{
          span: 20,
        }}
        rules={[
          {
            required: true,
            message: '商品名必须输入!',
          },
        ]}
      >
        <Input />
      </Form.Item>

      <Form.Item
        label="商品价格"
        name="price"
        wrapperCol = {{
          span: 2,
        }}
        rules={[
          {
            required: true,
            message: '商品价格必须输入!',
          },
        ]}
      >
        <Input />
      </Form.Item>

      <Form.Item
      label="上下架"
        name="onsale"
        valuePropName="checked"
      >
       <Switch checkedChildren="开启" unCheckedChildren="关闭"  />
      </Form.Item>

      <Form.Item
        label="商品分类"
        name="pid"
        rules={[
          {
            required: true,
            message: '商品分类必填!',
          },
        ]}
      >
        <Select
      defaultValue="lucy"
      style={{
        width: 120,
      }}
      options={options}
    />
      </Form.Item>

      <Form.Item
        label="描述"
        name="desc"
        wrapperCol = {{
          span: 20,
        }}
        
      >
        <TextArea rows={3} />
      </Form.Item>

      <Form.Item
        label="商品封面"
        
      
      >
         <Upload {..._props}>
    <Button icon={<UploadOutlined  />}>点击上传</Button>
  </Upload>
  <Image src={thumb} width={80}/>
      </Form.Item>

      <Form.Item
        label="商品内容"
        name="password"
      
      >
           {/* 富文本编辑器 */}
           <div style={{border: '1px solid #999'}}>
            <Toolbar
              editor={editor}
              defaultConfig={toolbarConfig}
              mode="default"
              style={{ borderBottom: '1px solid #ccc' }}
            />
            <Editor
              defaultConfig={editorConfig}
              value={html}
              onCreated={setEditor}
              onChange={editor => setHtml(editor.getHtml())}
              mode="default"
              style={{ height: '500px', overflowY: 'hidden' }}
            />
          </div>
          {/* /富文本编辑器 */}
      </Form.Item>


      <Form.Item
        wrapperCol={{
          offset: 8,
          span: 16,
        }}
      >
        <Button type="primary" htmlType="submit">
          确定提交
        </Button>
      </Form.Item>
    </Form>
  ;
    </div>
  )
}
export default ItemAdd
